package com.pds.web.company.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.mapper.FileUploadMapper;
import com.pds.system.mapper.SysUserMapper;
import com.pds.utils.FileUtil;
import com.pds.web.app.mapper.AppStationOpsMapper;
import com.pds.web.area.mapper.AreaMapper;
import com.pds.web.category.entity.PdsCategory;
import com.pds.web.category.mapper.PdsCategoryMapper;
import com.pds.web.category.vo.CategoryStandardVO;
import com.pds.web.company.domain.PdsCompanyStationInfo;
import com.pds.web.company.domain.PdsCompanyStationOps;
import com.pds.web.company.domain.PdsCompanyStationOpsDevice;
import com.pds.web.company.domain.PdsCompanyStationOpsForm;
import com.pds.web.company.mapper.PdsCompanyStationMapper;
import com.pds.web.company.service.PdsCompanyStationService;
import com.pds.web.industry.entity.Industry;
import com.pds.web.industry.mapper.IndustryMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PdsCompanyStationServiceImpl implements PdsCompanyStationService {

    private static Logger log = LoggerFactory.getLogger(PdsCompanyStationServiceImpl.class);
    @Autowired
    PdsCompanyStationMapper stationMapper;
    @Autowired
    FileUploadMapper fileUploadMapper;
    @Autowired
    PdsCategoryMapper pdsCategoryMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    AppStationOpsMapper appStationOpsMapper;
    @Autowired
    AreaMapper areaMapper;
    @Autowired
    IndustryMapper industryMapper;

    /**
     * 添加企业站房，无id新增，有id修改
     *
     * @param info
     */
    @Override
    public PdsCompanyStationInfo add(PdsCompanyStationInfo info) {
        log.info("企业站房信息编辑:{}", info);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(info.getId() == null){
            //新增
            info.setCompanyId(user.getDept().getOrganizationId());
            info.setCreateBy(user.getNickName());
            stationMapper.insert(info);
        }else {
            //修改
            info.setUpdateBy(user.getNickName());
            stationMapper.updateById(info);
        }
        return info;
    }

    /**
     * 删除站房
     *
     * @param id 站房id
     * @return
     */
    @Override
    public void deleteStation(Long id) {
        log.info("删除站房:{}", id);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        PdsCompanyStationInfo info = new PdsCompanyStationInfo();
        info.setId(id);
        info.setStatus("1");
        info.setUpdateBy(user.getNickName());
        stationMapper.updateById(info);
    }

    /**
     * 添加企业站房运维信息
     *
     * @param opsInfo
     */
    @Override
    public void addOpsInfo(PdsCompanyStationOps opsInfo) {
        log.info("企业站房运维信息编辑:{}", opsInfo);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(opsInfo.getOpsId()== null) {
            ///新增
            opsInfo.setCreateBy(user.getNickName());
            opsInfo.setStatus("0");
            stationMapper.addOpsInfo(opsInfo);
        } else {
            //更新
            opsInfo.setUpdateBy(user.getNickName());
            stationMapper.updateOpsInfo(opsInfo);
        }
    }


    /**
     * 查询企业站房列表
     * @param params 搜索条件
     *            - companyName 企业名称/MN号/站房名称
     *            - supervisionLevel 监管级别:1重点、2非重点
     *            - area 区域id
     *            - emissionType 排放类型:1一般废水、2污水处理、3一般废气、4VOCs废气、5垃圾焚烧
     *            - industry 所属行业
     *            - opsOrganizationId 运维机构
     */
    @Override
    public Map getCompanyStationList(Map params) {
        //环保局查全部、企业查自己、运维机构查负责的企业
        SysUser user = SecurityUtils.getLoginUser().getUser();
        int type = user.getDept().getType();
        Long companyId = user.getDept().getOrganizationId();
        String industryId ="";
        if(ObjectUtil.isNotEmpty(params.get("industry"))){
            //查询所有下级的行业
            industryId = String.valueOf(params.get("industry"));
            List<Industry> allIndustry = getAllIndustryByParentId(industryId);
            if(CollectionUtils.isNotEmpty(allIndustry)) {
                industryId += ","+allIndustry.stream().distinct().map(i -> i.getIndustryId()).collect(Collectors.joining(","));
                params.put("industry", industryId );
            }
        }
        List<Map> list = stationMapper.getCompanyStationList(type,companyId,params);
        if(list==null || list.size()<=0){
            Map res = new HashMap(2);
            res.put("total", 0L);
            res.put("rows", null);
            return res;
        }
        for (Map map : list) {
            //运维人员
            if(map.get("opsEngineer")!=null){
                //查询
                List<SysUser> sysUsers = sysUserMapper.selectUserByIds(String.valueOf(map.get("opsEngineer")));
                String opsEngineerName = sysUsers.stream().map(sysUser -> sysUser.getNickName()).collect(Collectors.joining(","));
                map.put("opsEngineerName",opsEngineerName);
            }
            //区域
            if(map.get("county")!=null){
                String county = areaMapper.selectAddressByCode(String.valueOf(map.get("county")));
                map.put("county",county);
            }
        }

        Map<Object, List<Map>> map = list.stream().collect(Collectors.groupingBy(m -> m.get("companyName")));
        List<Map> result = new ArrayList<>(map.size());
        map.forEach((k,v)->{
            Map<String, Object> temp = new HashMap<>();
            temp.put("companyName", k);
            temp.put("companyId", v.get(0).get("id"));
            temp.put("stationList", v);
            temp.put("industryName", v.get(0).get("industryName"));
            temp.put("pollutionDischargePermit", "");
            //查询企业排污许可证信息
            if(ObjectUtil.isNotEmpty(v.get(0).get("pollutionDischargePermitId"))){
                String fileId = String.valueOf(v.get(0).get("pollutionDischargePermitId"));
                FileUpload fileUpload = fileUploadMapper.selectFileUploadById(fileId);
                Map fileInfo = FileUtil.structureFile(fileUpload);
                temp.put("pollutionDischargePermit", fileInfo);
            }
            result.add(temp);
        });
        //数据封装后原分页失效，需要重新计算总数量
        long total = new PageInfo<>(list).getTotal();
        Map res = new HashMap(2);
        res.put("total", total);
        res.put("rows", result);
        return res;
    }

    /**
     * 查询所有下级的行业
     * @param industry
     * @return
     */
    private List<Industry> getAllIndustryByParentId(String industry) {
        QueryWrapper<Industry> wrapper = new QueryWrapper();
        wrapper.in("parent_id",industry.split(","));
        List<Industry> list = industryMapper.selectList(wrapper);
        if(CollectionUtils.isNotEmpty(list)) {
            String parentIds = list.stream().map(item -> item.getIndustryId()).collect(Collectors.joining(","));
            list.addAll(getAllIndustryByParentId(parentIds));
            return list;
        }else {
            return Lists.newArrayList();
        }
    }

    /**
     * 添加企业站房运维仪器信息
     *
     * @param device
     */
    @Override
    public void addDevice(PdsCompanyStationOpsDevice device) {
        log.info("企业站房运维仪器信息编辑:{}", device);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (device.getId() == null) {
            //新增
            device.setCreateBy(user.getNickName());
            device.setStatus("0");
            stationMapper.addDevice(device);
        } else {
            //更新
            device.setUpdateBy(user.getNickName());
            stationMapper.updateDevice(device);
        }

    }



    /**
     * 查询站房详细
     *
     * @param stationId 站房id
     * @return
     */
    @Override
    public Map getDetail(Long stationId) {
        log.info("查询站房详细:stationId={}", stationId);
        PdsCompanyStationInfo info = stationMapper.getCompanyStationDetail(stationId);
        if(StringUtils.isNotEmpty(info.getStationImageId())) {
            List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(info.getStationImageId().split(","));
            if(fileUploads!= null && fileUploads.size()>0) {
                List<Map> files = new ArrayList<>(fileUploads.size());
                for (FileUpload upload : fileUploads) {
                    files.add(FileUtil.structureFile(upload));
                }
                info.setStationImage(files);
            }
        }
        //查询运维信息
        PdsCompanyStationOps opsInfo = stationMapper.getOpsInfo(stationId);
        //查询附件信息
        String fileIds = "";
        if(opsInfo!=null){
            fileIds += opsInfo.getOpsContractFileId()==null ? "" : ","+opsInfo.getOpsContractFileId();
            fileIds += opsInfo.getOpsPlanFileId()==null? "" : ","+opsInfo.getOpsPlanFileId();
            fileIds += opsInfo.getAcceptReportFileId()==null? "" : ","+opsInfo.getAcceptReportFileId();
        }
        if(!"".equals(fileIds)){
            List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(fileIds.substring(1).split(","));
            for (int i = 0; i < fileUploads.size(); i++) {
                FileUpload fileUpload = fileUploads.get(i);
                if(fileUpload.getAttachmentId().equals(opsInfo.getOpsContractFileId())){
                    opsInfo.setOpsContractFile(FileUtil.structureFile(fileUpload));
                }else if(fileUpload.getAttachmentId().equals(opsInfo.getOpsPlanFileId())){
                    opsInfo.setOpsPlanFile(FileUtil.structureFile(fileUpload));
                }else if(fileUpload.getAttachmentId().equals(opsInfo.getAcceptReportFileId())){
                    opsInfo.setAcceptReportFile(FileUtil.structureFile(fileUpload));
                }
            }
        }
        //查询运维工程师名字
        if(StringUtils.isNotEmpty(opsInfo.getOpsEngineer())) {
            List<SysUser> sysUsers = sysUserMapper.selectUserByIds(opsInfo.getOpsEngineer());
            String userNames = sysUsers.stream().map(sysUser -> sysUser.getNickName()).collect(Collectors.joining(","));
            opsInfo.setOpsEngineerName(userNames);
        }

        //查询仪器信息
        List<PdsCompanyStationOpsDevice> devices = stationMapper.getDevices(stationId);
        //检测因子查询
        if(devices!=null && devices.size()>0) {
            for (PdsCompanyStationOpsDevice device : devices) {
                if (StringUtils.isNotEmpty(device.getMonitoringFactor())) {
                    PdsCategory pdsCategory = new PdsCategory();
                    String[] ids = device.getMonitoringFactor().split(",");
                    Set<String> set = Arrays.stream(ids).collect(Collectors.toSet());
                    pdsCategory.setIds(set);
                    List<CategoryStandardVO> categoryStandardVOS = pdsCategoryMapper.selectList(pdsCategory);
                    String collect = categoryStandardVOS.stream().map(CategoryStandardVO::getName).collect(Collectors.joining("、"));
                    device.setMonitoringFactorStr(collect);
                }
            }
        }

        Map result = new HashMap(3);
        result.put("baseInfo",info);
        result.put("opsInfo",opsInfo);
        result.put("devices",devices);
        return result;
    }

    /**
     * 查询仪器详情
     *
     * @param id 仪器id
     * @return
     */
    @Override
    public PdsCompanyStationOpsDevice getDeviceDetail(Long id) {
        PdsCompanyStationOpsDevice device = stationMapper.getDeviceById(id);
        //查询仪器图片
        if(StringUtils.isNotEmpty(device.getDeviceImageId())){
            List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(device.getDeviceImageId().split(","));
            if(fileUploads!= null && fileUploads.size()>0) {
                List<Map> files = new ArrayList<>(fileUploads.size());
                for (FileUpload upload : fileUploads) {
                    files.add(FileUtil.structureFile(upload));
                }
                device.setDeviceImage(files);
            }
        }
        //查询因子
        if(StringUtils.isNotEmpty(device.getMonitoringFactor())){
            PdsCategory pdsCategory = new PdsCategory();
            String[] ids = device.getMonitoringFactor().split(",");
            Set<String> set = Arrays.stream(ids) .collect(Collectors.toSet());
            pdsCategory.setIds(set);
            List<CategoryStandardVO> categoryStandardVOS = pdsCategoryMapper.selectList(pdsCategory);
            String collect = categoryStandardVOS.stream().map(CategoryStandardVO::getName).collect(Collectors.joining("、"));
            device.setMonitoringFactorStr(collect);
        }
        return device;
    }

    /**
     * 查询站房运维表单列表
     *
     * @param map
     * @return
     */
    @Override
    public List<Map> getOpsFormList(Map map) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        map.put("userType",user.getDept().getType());
        map.put("deptId",user.getDept().getOrganizationId());
        List<Map> list = stationMapper.selectTaskCount(map);
        return list;
    }

    /**
     * 站房运维统计
     *
     * @param stationId 站房id
     * @param type      类型：month本月、year本年，其他为全部
     */
    @Override
    public List<Map> getStationOpsCount(Long stationId, String type) {
        Map params = new HashMap();
        PdsCompanyStationInfo stationInfo = stationMapper.getCompanyStationDetail(stationId);
        if(stationInfo.getEmissionType().startsWith("1")){
            params.put("emissionType","1");
        }else {
            params.put("emissionType","2");
        }
        params.put("stationId",stationId);
        if("month".equals(type)||"year".equals(type)) {
            Map timePeriod = DateUtils.getTimePeriod(type);
            params.putAll(timePeriod);
        }
        return stationMapper.getStationOpsCount(params);
    }

    /**
     * 环保局给运维表单评分
     *
     * @param id    运维表单id
     * @param score 评分
     * @return
     */
    @Override
    public void epbScore(Long id, Double score) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        PdsCompanyStationOpsForm form = new PdsCompanyStationOpsForm();
        form.setId(id);
        form.setEpbScore(score);
        form.setUpdateBy(user.getNickName());
        form.setStatus(4);
        appStationOpsMapper.update(form);
    }

    /**
     * 查询指定站房的运维机构信息
     *
     * @param stationId
     * @return
     */
    @Override
    public List<Map> getStationOpsOrganization(Long stationId) {
        return appStationOpsMapper.getStationOpsOrganization(stationId);
    }

    /**
     * 查询指定站房的运维工程师信息
     *
     * @param stationId
     * @param organizationId
     * @return
     */
    @Override
    public List<Map> getStationOpsEngineer(Long stationId, Long organizationId) {
        return appStationOpsMapper.getStationOpsEngineer(stationId,organizationId);
    }
}
